package uit.mmt02.activity;

import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;

import uit.mmt02.R;
import uit.mmt02.xuly.ConvertMessageToList;
import uit.mmt02.dataAccess.db_email;
import uit.mmt02.doituong.OneMail;
import uit.mmt02.adapter.myadapter;
import uit.mmt02.doituong.showToast;
import uit.mmt02.mailControl.YahooControl;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class getYahooActivity extends Activity
{
	final static String tag   = "getYAHOOactivity";
	YahooControl g ;
	
	//---------------------------------Copy...
	
	final static String KEY_USERNAME_LOGIN = "USERNAMELOGIN"; // nhan USERVA PASS tu showmail activity gui toi de login
	final static String KEY_PASSWORD_LOGIN = "PASSWORDLOGIN";
	static final String FROM = "from";
	static final String BODY = "body";
	static final String SUB = "sub";
	static final String DATE = "date";
	static final String TIME = "time";
	static final String TO = "to";
	//option......................
	static final String ATTACH = "attach";
	static final String VOICE = "voice";
	static final String ENCRYPT = "encrypt";
	String username;
	String password;
	ArrayAdapter<OneMail>adapter;
	Message[]message;
	showToast d;
	List<OneMail>list; //list truyen vao adapter
	int n ; // so mail
	Bundle bundle; //nhan username va password
	ListView listview; //lay listview
	View view; // view footer
	LayoutInflater Linflater;
	Button btn_more, btn_logout;
	
	//
	
	db_email mydb;
	Cursor mCursor;
	int i_start_query_more = 6;
	boolean flag_getmessage = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_email_login);
		listview = (ListView)findViewById(R.id.listview_list_email);
		d = new showToast(getBaseContext());
		list = new ArrayList<OneMail>();	
		//
		Linflater = getLayoutInflater();
		view = Linflater.inflate(R.layout.footer_list_mail, null);
		//
		bundle = getIntent().getExtras();
		username = bundle.getString(KEY_USERNAME_LOGIN);
		password = bundle.getString(KEY_PASSWORD_LOGIN);
		Log.v(tag, "Nhan duoc : " + username + " | " + password);
		//goi class loadmail chay nhu 1 tien trinh moi
		new load_Yahoo_Mail().execute(tag);
		//-------------
		btn_more = (Button)view.findViewById(R.id.btn_foot_more);
		
		btn_more.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				d.showmess(getResources().getString(R.string.addmore) + " . . .");
				add_more_mail_to_list();
//				new load_more_mail().execute("more");
//				add_more_email();
//				pdialog1.dismiss();
//				new Runnable() {
//					public void run() {
//						add_more_email();
//						adapter.notifyDataSetChanged();
//						pdialog1.dismiss();
//					}
//				}.run();
//				adapter.notifyDataSetChanged();
//				new Thread(new Runnable() {
//					
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub
//						add_more_email();
//						adapter.notifyDataSetChanged();
//						pdialog1.dismiss();
//						
//					}
//				}).start();
			}
		});
		
		btn_logout = (Button)view.findViewById(R.id.btn_foot_logout);
		btn_logout.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO REMOVE USERNAME NAY RA KHOI CSDL
				startActivity(new Intent(getYahooActivity.this, ListMailActivity.class));
				
			}
		});
		
		TextView txt_email = (TextView)view.findViewById(R.id.txt_foot_email);
		txt_email.setText(username);
	}
	
	// asyncTask Load mail
		private class load_Yahoo_Mail extends AsyncTask<String,String	, Message[]>
		{
			ProgressDialog pdialog = new ProgressDialog(getYahooActivity.this);
			
			@Override
			protected void onPreExecute() 
			{
				String str = getResources().getString(R.string.connect_yahoo); 
				pdialog.setMessage(str + " \n " +username);
				pdialog.show();
				super.onPreExecute();
			}

			@Override
			protected Message[] doInBackground(String... params) 
			{
				// TODO Auto-generated method stub
//				Log.v(tag, "doinBackGroud");
//				g = new YahooControl(username, password);
//				message = g.getmail();
//				ConvertMessageToList cv = new ConvertMessageToList();
//				list = cv.convert2(message);
//				adapter = new myadapter(getYahooActivity.this, list);
////				LayoutInflater inflater = getLayoutInflater();
////				view = inflater.inflate(R.layout.footer_list_mail, null);
//				Log.v(tag, "end doinBackGroud");
//				return message;
				doinbackGround();
				return null;
				
			}
			@Override
			protected void onPostExecute(Message[] resultMes) {
				// TODO Auto-generated method stub
				Log.v(tag,"on post");
				
				listview.addFooterView(view);
				listview.setAdapter(adapter);
				pdialog.dismiss();
				super.onPostExecute(resultMes);
			}
			
		}
		
		
		
		
		//ham add them 5 email vao list
		@SuppressWarnings("unused")
		private void add_more_email() {
			// TODO Auto-generated method stub
			try
			{
				n = list.size(); // so mail da dc load
				int n_tongmail = message.length; // tong so mail
				int n_batdautai = n_tongmail -n-1;
				Log.v(tag, "get dc " + n_tongmail + "get tu " + n_batdautai);
				ConvertMessageToList cv2 = new ConvertMessageToList();
//				for (int i = 10 ; i > 5 ; i--)
				for (int i = n_batdautai ; i > n_batdautai-5 ; i--)
				{
					if(i >= 0)
					{
						OneMail om = cv2.get1mail(message, i);
						adapter.add(om);
						Log.v(tag, "get dc " + i);
					}
					
				}
//				adapter.notifyDataSetChanged();
			}
			
			catch (Exception e) {
				// TODO: handle exception
				Log.i(tag, "Loi add 5 email" + e.toString());
			}

		}
		
		//tao 1 tien trinh load them email rieng, 1 dialog bao ng dung doi
		@SuppressWarnings("unused")
		private class load_more_mail extends AsyncTask<String, String, String>
		{
			ProgressDialog pdialog = new ProgressDialog(getYahooActivity.this);
			
			@Override
			protected void onPreExecute() 
			{
//				pdialog.setTitle("Get Mail");
				pdialog.setMessage("Ä�ang táº£i ....");
				pdialog.show();
				super.onPreExecute();
			}

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
			
			// lay 5 mail tu csdl cho vao list
				
				return null;
			}
			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
//				adapter.notifyDataSetChanged();
				pdialog.dismiss();
				super.onPostExecute(result);
				
			}
			
		}
		
		public void doinbackGround()
		{
			// kiem tra CSDL cua user
			try
			{
			Log.v(tag, "doinBackGroud");
			g = new YahooControl(username, password);
			String []str = username.split("@");
			String db_name = "db_" + str[0] +"_yahoo";
			mydb = new db_email(this, db_name);
			mydb.open();
			mCursor = mydb.query(1,5);
			Log.v(tag, "GGGGGGGGGG");
			if(mCursor.getCount() == 0)
			{
				Log.v(tag, "GGGGGGGGGGhhhhhhhh");
				mCursor.close();
				message = g.getmail();
				flag_getmessage = true;
				mydb.save_msg_to_db(message);
				Log.v(tag, "save mail vao csdl tai khoan " + username);
				mCursor = mydb.query(1,5);
			}
			Log.v(tag, "SO ROW save: " + mCursor.getCount());
			if(mCursor.moveToFirst()) // neu co csdk , dua 5 mail vao list,adapter
			{
				do
				{
					int id = mCursor.getInt(0);
					String from = mCursor.getString(1);
					String to = mCursor.getString(2);
					String sub = mCursor.getString(3);
					String body = mCursor.getString(4);
					String time = mCursor.getString(5);
					int flag_attach = mCursor.getInt(6);
					int flag_favorite = mCursor.getInt(7);
					int flag_encrypt = mCursor.getInt(8);
					int flag_voice = mCursor.getInt(9);
					int flag_read = mCursor.getInt(10);
					String str_attach = mCursor.getString(11);
					boolean f_att = (flag_attach == 1 ? true:false);
					boolean f_fa = (flag_favorite == 1 ? true:false);
					boolean f_en = (flag_encrypt ==1 ? true:false);
					boolean f_voi = (flag_voice==1?true:false);
					boolean f_read = (flag_read == 1 ? true:false);
					OneMail om3 = new OneMail(id, from, to, 
							sub, body, time, f_att, f_fa, f_en, f_voi, f_read, str_attach);
					list.add(om3);
					
				}while (mCursor.moveToNext());
			}
			if(flag_getmessage == false)//va kiem tra co ket noi mang
				message = g.getmail();
			adapter = new myadapter(this, list, message,db_name,username); //mes truyen vao adapter thuc hien update favorite
			mCursor.close();
			mydb.close();
			}catch (Exception e) {
				// TODO: handle exception
				Log.v(tag, "loi do in back");
			}
		}
		
		public void add_more_mail_to_list()
		{
			mydb.open();
			//duyet tu mail thu 6 , den mail 10, sau moi lan duyet , mail bat dau duyet se dc + 5;
			mCursor = mydb.query(i_start_query_more, i_start_query_more +4);
			Log.v(tag, "ADD_more_mail");
			//
			if(mCursor.moveToFirst() && mCursor.getCount() >= 1)
			{
				do
				{
					int id = mCursor.getInt(0);
					String from = mCursor.getString(1);
					String to = mCursor.getString(2);
					String sub = mCursor.getString(3);
					String body = mCursor.getString(4);
					String time = mCursor.getString(5);
					int flag_attach = mCursor.getInt(6);
					int flag_favorite = mCursor.getInt(7);
					int flag_encrypt = mCursor.getInt(8);
					int flag_voice = mCursor.getInt(9);
					int flag_read = mCursor.getInt(10);
					String str_attach = mCursor.getString(11);
					boolean f_att = (flag_attach == 1 ? true:false);
					boolean f_fa = (flag_favorite == 1 ? true:false);
					boolean f_en = (flag_encrypt ==1 ? true:false);
					boolean f_voi = (flag_voice==1?true:false);
					boolean f_read = (flag_read == 1 ? true:false);
					OneMail om3 = new OneMail(id, from, to, 
							sub, body, time, f_att, f_fa, f_en, f_voi, f_read, str_attach);
					list.add(om3);
//					adapter.add(om3);
					
				}while (mCursor.moveToNext());
			}else
			{
				d.showmess("tiep tuc get mail tu server online...");
			}
			
			i_start_query_more += 5;
			mCursor.close();
			mydb.close();
			adapter.notifyDataSetChanged();
			
		}
		public void refresh()
		{
			try
			{
				Log.v(tag, "Tien hanh refresh ...update CSDL...");
				mydb.open();
				mydb.removeALl();
				mydb.close();
				list.removeAll(list);
//				adapter.notifyDataSetChanged();
				new load_Yahoo_Mail().execute("refresh");
				adapter.notifyDataSetChanged();
			}catch (Exception e) {
				// TODO: handle exception
				Log.v(tag, "khong the refresh");
			}
		}
		//menu
				// tao menu 
				@Override
				public boolean onCreateOptionsMenu(Menu menu) {
					// TODO Auto-generated method stub
					MenuInflater inflater = getMenuInflater();
					inflater.inflate(R.menu.layout_menu, menu);
					return super.onCreateOptionsMenu(menu);
				}
				//khi click vao menu item
				@Override
				public boolean onOptionsItemSelected(MenuItem item) 
				{
					// TODO Auto-generated method stub
					switch (item.getItemId()) 
					{
					case R.id.item_layout_refresh:
						d.showmess("refresh");
						refresh();
						break;
					case R.id.item_layout_compose:
						d.showmess("new mail compose");
						Intent iii = new Intent(this, uit.mmt02.activity.newmailActivity.class);
						iii.putExtra(KEY_USERNAME_LOGIN, username);
						iii.putExtra(KEY_PASSWORD_LOGIN, password);
						startActivity(iii);
					case R.id.item_layout_search:
						d.showmess("serach");
						break;
					case R.id.item_layout_markAll:
						mark_all();
						break;
					case R.id.item_layout_unMark:
						unmark_all();
						break;
					case R.id.item_layout_delete:
//						d.showmess("delete ...");
//						delete_mess();
						Alert_yes_no_delete();
						break;
					default:
						break;
					}
					return super.onOptionsItemSelected(item);
				}
				
				public void mark_all()
				{
					int i_list = list.size();
					for(int i = 0 ; i < i_list; i ++)
					{
						list.get(i).setCheck(true);
					}
					adapter.notifyDataSetChanged();
				}
				public void unmark_all()
				{
					int i_list = list.size();
					for(int i = 0 ; i < i_list; i ++)
					{
						list.get(i).setCheck(false);
					}
					adapter.notifyDataSetChanged();
				}
				
				public void delete_mess()
				{
					int i_list = list.size();
					ConvertMessageToList cv = new ConvertMessageToList();
					mydb.open();
					List<Integer>i_del = new ArrayList<Integer>();
					
					for(int i = 0 ; i < i_list; i ++)
					{
						OneMail o3 = list.get(i);
						if(o3.isCheck()) // neu dc check
						{
							Log.v(tag, "Tien hanh delete..." + i);
							cv.delete_message(message, message.length - i - 1);
							mydb.remove_by_stt(i+1);
							i_del.add(i);
						}
					}
					for(int i : i_del)
					{
						list.remove(i);
					}
					mydb.close();
					adapter.notifyDataSetChanged();
				}
				
				public void Alert_yes_no_delete()
				{
					AlertDialog.Builder alert = new AlertDialog.Builder(this);
					alert.setMessage(getResources().getString(R.string.alert_yes_no));
					alert.setPositiveButton("OK", new OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
//							check1 = true;
							delete_mess();
						}
					});
					alert.setNegativeButton("Cancel", new OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							
						}
					});
					AlertDialog al_dialog = alert.create();
					al_dialog.setIcon(R.drawable.err_happy_5);
					al_dialog.show();
				}

}
